from av_manager.plat_form.plat_base import PlatFormBase
from av_manager.plat_form.youtube.ytb_api import YoutubeAPI
from common.file_utils import create_dir


class YouTube(PlatFormBase, YoutubeAPI):

    def __init__(self, api_key):
        super().__init__(api_key)

    def set_auth(self, api_key):
        self.set_api_key(api_key)

    def get_brief_channel_by_id(self, channel_id=None) -> list:
        """
        获取频道简介列表
        :param channel_id:
        :param channel_name:
        :return:
        """
        channel_info = self.get_channel_by_id(channel_id)
        data = self.tidy_channels(channel_info)
        return data

    @staticmethod
    def tidy_channels(channel_list):
        items = channel_list.get("items")
        data = []
        if not items:
            return data
        for channel in items:
            snippet = channel.get("snippet")
            statistics = channel.get("statistics")
            data.append(dict(
                channel_name=snippet.get("title"),
                description=snippet.get("description"),
                birthday=snippet.get("publishedAt"),
                avatar=snippet.get("thumbnails").get("default"),
                v_count=statistics.get("videoCount"),
                s_count=statistics.get("subscriberCount"),
                plat_code="YouTube"
            ))
        return data

    def get_videos_in_channel(self, *args, **kwargs):
        return self.handle_videos_data(self.video_search_in_channel(*args, **kwargs))

    def handle_videos_data(self, data):
        return dict(
            count=data.get("pageInfo").get("totalResults"),
            next=data.get("nextPageToken"),
            previous=data.get("prevPageToken"),
            results=[dict(
                video_id=i.get("id").get("videoId"),
                source=self.__class__.__name__,
                name=i.get("snippet").get("title"),
                description=i.get("snippet").get("description"),
                thumbnail=i.get("snippet").get("thumbnails").get("default"),
                publish_time=i.get("snippet").get("publishTime"),
                look_status=i.get("snippet").get("liveBroadcastContent")
            ) for i in data.get("items")],
        )

    def get_video_detail(self, *args, **kwargs):
        return self.get_video_info(*args, **kwargs)

    @staticmethod
    def get_video_url(video_id):
        return f"https://www.youtube.com/watch?v={video_id}"

    def download_video(self, video_id, file_name, suffix="webm"):
        from av_manager.plat_form.youtube.downloader import CustomYoutubeDownloader
        url = self.get_video_url(video_id)
        # YoutubeDownloader 无法指定视频格式
        suffix = "webm"
        create_dir(file_name)
        downloader = CustomYoutubeDownloader(file_name, url, suffix)
        res = downloader.start()
        res.update(suffix=suffix, file_name=downloader.fname)
        return res
